import jsonpath


class GetKeyword:
    @staticmethod
    def get_keyword(source_data, keyword):
        """
        获取关键字对应的值,默认获取第一个值,如果不存在,返回False
        :param source_data: 数据源
        :param keyword: 关键字
        :return:
        """
        try:
            return jsonpath.jsonpath(source_data, f'$..{keyword}')[0]
        except:
            print(f'关键字{keyword}不存在')
            return False

    @staticmethod
    def get_keywords(source_data, keyword):
        """
        获取关键字对应所有值,如果不存在,返回False
        :param source_data: 数据源
        :param keyword: 关键字
        :return:
        """
        try:
            return jsonpath.jsonpath(source_data, f'$..{keyword}')
        except:
            print(f'关键字{keyword}不存在')
            return False


if __name__ == '__main__':
    test_data = {
        'status_code': 200,
        'headers': {'Vary': 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers',
                    'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block',
                    'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate', 'Pragma': 'no-cache',
                    'Expires': '0', 'X-Frame-Options': 'DENY', 'Content-Type': 'application/json',
                    'Transfer-Encoding': 'chunked', 'Date': 'Tue, 13 Jun 2023 03:49:27 GMT', 'Keep-Alive': 'timeout=60',
                    'Connection': 'keep-alive'},
        'body': {'code': 200,
                 'data': {
                     'token': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE2ODY2MjgxNjc0NjcsImV4cCI6MTY4NzIzMjk2N30.tUcPmhqJQxbvUJdRcFiL-NwN43g5NuYoeHBfn8YVb3qG0Iw05wV4Q5xhZHQ5pHyNq83MYX7tJAmdJLNBDn6j6Q',
                     'tokenHead': 'Bearer '},
                 'message': '操作成功'},
        'response_time': 130
    }
    print(GetKeyword.get_keywords(test_data,"code"))